//
//  FLLNewestViewController.m
//  FLLGodOfCooking
//
//  Created by LL.F on 16/9/2.
//  Copyright © 2016年 LL.F. All rights reserved.
//

#import "FLLNewestViewController.h"
#import "ZWYNetTool.h"
#import "FLLNewestModel.h"
#import "NewestData.h"
#import "NewestSecData.h"
#import "NewestTopics.h"
#import "Masonry.h"
#import "FLLNewestCollectionViewCell.h"
#import "FLLMacro.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "FLLWorksDetailViewController.h"

@interface FLLNewestViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *newestCollectionView;
@property (nonatomic, strong) FLLNewestModel *fllNewestModel;
@property (nonatomic, strong) NSMutableArray<NewestSecData *> *secDataArray;
@property (nonatomic, assign) NSInteger pageCount;
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, strong) NSString *post_ID;
@property (nonatomic, strong) NSMutableArray<NewestTopics *> *post_IDArray;
@property (nonatomic, strong) NSMutableArray *id_DataArray;
@property (nonatomic, copy) NSString *bodyString;
@end

@implementation FLLNewestViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _pageCount = 1;
    self.post_ID = [NSString stringWithFormat:@"%zd", 0];
    self.navigationItem.title = self.titleLabel;
    self.id_DataArray = [NSMutableArray array];
    [self createPOSTRequest];
    [self createNewestCollectionView];
}
- (void)createNewestCollectionView
{
    
    UICollectionViewFlowLayout *newestLayout = [[UICollectionViewFlowLayout alloc] init];
    newestLayout.minimumInteritemSpacing = CellMargin;
    newestLayout.minimumLineSpacing = 0;
    newestLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.newestCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:newestLayout];
    _newestCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_newestCollectionView];
    [_newestCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(0);
    }];
    _newestCollectionView.delegate = self;
    _newestCollectionView.dataSource = self;
    [_newestCollectionView registerNib:[UINib nibWithNibName:@"FLLNewestCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"newestCollectionCell"];
#pragma mark -- 上拉加载 下拉刷新
    self.newestCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isRefresh = NO;
        if (_is_marrow == 1) {
            [self createMarrowRequest];
        } else if (_topicID.length == 0 && _is_marrow == 0) {
            [self createNewestRequest];
        } else {
            [self createTopicRequest];
        }
        [self.newestCollectionView.mj_header endRefreshing];
    }];
    
    self.newestCollectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _isRefresh = YES;
        if (_is_marrow == 1) {
            [self createMarrowRequest];
        } else if (_topicID.length == 0 && _is_marrow == 0) {
            [self createNewestRequest];
        } else {
            [self createTopicRequest];
        }
        [self.newestCollectionView.mj_footer endRefreshing];
    }];
    
    
}

- (void)createPOSTRequest
{
    
    
    if (self.is_marrow == 1) {
        [self createMarrowRequest];
    } else if (_topicID.length != 0) {
            [self createTopicRequest];
        } else {
    
            [self createNewestRequest];
        }

}
// "最新"的更多
- (void)createNewestRequest
{

    // 起始或者刷新
    if (_isRefresh == NO) {
        
        _post_ID = 0;
        
        // 加载
    } else {
        
        _post_ID = _id_DataArray.lastObject;
        
    }
    
    
    self.bodyString = [NSString stringWithFormat:@"is_marrow=0&page=1&methodName=ShequList&last_id=%@&size=20&version=4.40&", _post_ID];
    [ZWYNetTool POST:@"http://api.izhangchu.com/ HTTP/1.1" andBody:_bodyString andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        self.fllNewestModel = [FLLNewestModel modelWithDic:result];
        // 起始或者刷新
        if (_isRefresh == NO) {
            // 数组移除放到网络请求里面写
            [self.secDataArray removeAllObjects];
            [self.id_DataArray removeAllObjects];
            self.secDataArray = (NSMutableArray *)self.fllNewestModel.data.data;
            [self.id_DataArray addObject:(id)self.secDataArray.lastObject.id_Data];
            // 加载
        } else {
            
            [self.secDataArray addObjectsFromArray:(NSMutableArray *)self.fllNewestModel.data.data];
            [self.id_DataArray addObject:(id)self.secDataArray.lastObject.id_Data];
            
        }
        [self.newestCollectionView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];


}
// "精选作品"的更多
- (void)createMarrowRequest
{

    
    // 起始或者刷新
    if (_isRefresh == NO) {
       _pageCount = 1;
        
        // 加载
    } else {
        _pageCount++;
        
    }

    self.bodyString = [NSString stringWithFormat:@"is_marrow=1&page=%zd&methodName=ShequList&size=20&version=4.40&", _pageCount];

[ZWYNetTool POST:@"http://api.izhangchu.com/ HTTP/1.1" andBody:_bodyString andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
    
    self.fllNewestModel = [FLLNewestModel modelWithDic:result];
    // 起始或刷新
    if (_isRefresh == NO) {
        [self.secDataArray removeAllObjects];
        self.secDataArray = (NSMutableArray *)self.fllNewestModel.data.data;
    } else {
        [self.secDataArray addObjectsFromArray:(NSMutableArray *)self.fllNewestModel.data.data];
    }
    [self.newestCollectionView reloadData];
    
    
} andFailureBlock:^(NSError *error) {
    
}];

}
// 其他话题的更多
- (void)createTopicRequest
{
    
    // 起始或者刷新
    if (_isRefresh == NO) {
        _pageCount = 1;
        
        // 加载
    } else {
        _pageCount++;
        
    }
    self.bodyString = [NSString stringWithFormat:@"is_marrow=0&topic_id=%@&page=%zd&methodName=ShequList&size=20&version=4.40&", _topicID, _pageCount];
    [ZWYNetTool POST:@"http://api.izhangchu.com/ HTTP/1.1" andBody:_bodyString andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        self.fllNewestModel = [FLLNewestModel modelWithDic:result];
        // 起始或刷新
        if (_isRefresh == NO) {
            [self.secDataArray removeAllObjects];
            self.secDataArray = (NSMutableArray *)self.fllNewestModel.data.data;
        } else {
            [self.secDataArray addObjectsFromArray:(NSMutableArray *)self.fllNewestModel.data.data];
        }
        [self.newestCollectionView reloadData];
        
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    

    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return _secDataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    FLLNewestCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"newestCollectionCell" forIndexPath:indexPath];
   
    cell.grayLabel.backgroundColor = FLLLightGrayColor;
    cell.whiteLabel.backgroundColor = [UIColor whiteColor];
    [cell.dishImageView sd_setImageWithURL:[NSURL URLWithString:_secDataArray[indexPath.row].image] placeholderImage:[UIImage new] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
    }];
    [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:_secDataArray[indexPath.row].head_img] placeholderImage:[UIImage imageNamed:@"userHeadImage"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
    }];
    cell.userNameLabel.text = _secDataArray[indexPath.row].nick;
    cell.userNameLabel.font = [UIFont systemFontOfSize:15 * kWidthScale];
    cell.createTimeLabel.text = _secDataArray[indexPath.row].create_time;
    cell.createTimeLabel.font = [UIFont systemFontOfSize:14 * kWidthScale];
    cell.agreeCountLabel.text = _secDataArray[indexPath.row].agree_count;
    cell.agreeCountLabel.font = [UIFont systemFontOfSize:13 * kWidthScale];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    CGFloat itemWidth = (_newestCollectionView.bounds.size.width - CellMargin) / 2.0 ;
    CGFloat itemHeight = itemWidth / 32.0 * 42 ;
    return CGSizeMake(itemWidth, itemHeight);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *idString = self.secDataArray[indexPath.row].id_Data;
    FLLWorksDetailViewController *detailVC = [[FLLWorksDetailViewController alloc] init];
    detailVC.idString = idString;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}
- (void)setIs_marrow:(NSInteger)is_marrow
{

    _is_marrow = is_marrow;
    [self.newestCollectionView reloadData];
}
- (void)setTitleLabel:(NSString *)titleLabel
{

    _titleLabel = titleLabel;
    [self.newestCollectionView reloadData];
}
- (void)setTopicID:(NSString *)topicID
{

    _topicID = topicID;
    [self.newestCollectionView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
